import React, { useState, useEffect } from 'react';
import { 
  Row, 
  Col, 
  Card, 
  Button, 
  Input, 
  Select, 
  Pagination, 
  Spin, 
  message,
  Typography,
  Space,
  Image
} from 'antd';
import { 
  ShoppingCartOutlined, 
  EyeOutlined, 
  SearchOutlined 
} from '@ant-design/icons';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { bookApi, cartApi, authApi } from '../../api';

const { Meta } = Card;
const { Title } = Typography;
const { Option } = Select;

const Books = () => {
  const [loading, setLoading] = useState(false);
  const [books, setBooks] = useState([]);
  const [searchParams, setSearchParams] = useSearchParams();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 12,
    total: 0
  });
  
  // 搜索和筛选状态
  const [searchText, setSearchText] = useState(searchParams.get('search') || '');
  const [sortBy, setSortBy] = useState('createTime');
  const [sortOrder, setSortOrder] = useState('desc');
  
  const navigate = useNavigate();

  // 获取书籍列表
  const fetchBooks = async (page = 0, size = 12, search = '', sort = 'createTime', order = 'desc') => {
    setLoading(true);
    try {
      let response;
      if (search) {
        response = await bookApi.searchBooks(search, page, size);
      } else {
        response = await bookApi.getAllBooks(page, size);
      }
      
      if (response.success) {
        let bookList = response.data.content || [];
        
        // 客户端排序（如果后端不支持排序）
        if (sort === 'price') {
          bookList.sort((a, b) => {
            return order === 'asc' ? a.price - b.price : b.price - a.price;
          });
        } else if (sort === 'name') {
          bookList.sort((a, b) => {
            return order === 'asc' ? a.name.localeCompare(b.name) : b.name.localeCompare(a.name);
          });
        }
        
        setBooks(bookList);
        setPagination({
          current: page + 1,
          pageSize: size,
          total: response.data.totalElements || 0
        });
      } else {
        message.error(response.message || '获取书籍列表失败');
      }
    } catch (error) {
      console.error('获取书籍列表错误:', error);
      message.error('获取书籍列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const search = searchParams.get('search') || '';
    setSearchText(search);
    fetchBooks(0, pagination.pageSize, search, sortBy, sortOrder);
  }, [searchParams]);

  // 搜索处理
  const handleSearch = (value) => {
    setSearchText(value);
    if (value) {
      setSearchParams({ search: value });
    } else {
      setSearchParams({});
    }
    fetchBooks(0, pagination.pageSize, value, sortBy, sortOrder);
  };

  // 排序处理
  const handleSortChange = (value) => {
    const [sort, order] = value.split('-');
    setSortBy(sort);
    setSortOrder(order);
    fetchBooks(pagination.current - 1, pagination.pageSize, searchText, sort, order);
  };

  // 分页处理
  const handlePageChange = (page, pageSize) => {
    fetchBooks(page - 1, pageSize, searchText, sortBy, sortOrder);
  };

  // 查看书籍详情
  const viewBookDetail = (id) => {
    navigate(`/books/${id}`);
  };

  // 添加到购物车
  const addToCart = async (book) => {
    if (!authApi.isAuthenticated()) {
      message.warning('请先登录');
      navigate('/login');
      return;
    }

    try {
      const response = await cartApi.addToCart(book.id, 1);
      if (response.success) {
        message.success('已添加到购物车');
      } else {
        message.error(response.message || '添加到购物车失败');
      }
    } catch (error) {
      console.error('添加到购物车错误:', error);
      message.error('添加到购物车失败');
    }
  };

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <Title level={2}>全部书籍</Title>
        
        <Row gutter={16} align="middle" style={{ marginBottom: 16 }}>
          <Col flex="auto">
            <Input.Search
              placeholder="搜索书籍名称"
              allowClear
              enterButton={<SearchOutlined />}
              size="large"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              onSearch={handleSearch}
            />
          </Col>
          <Col>
            <Space>
              <span>排序：</span>
              <Select
                value={`${sortBy}-${sortOrder}`}
                onChange={handleSortChange}
                style={{ width: 150 }}
              >
                <Option value="createTime-desc">最新上架</Option>
                <Option value="createTime-asc">最早上架</Option>
                <Option value="price-asc">价格从低到高</Option>
                <Option value="price-desc">价格从高到低</Option>
                <Option value="name-asc">书名A-Z</Option>
                <Option value="name-desc">书名Z-A</Option>
              </Select>
            </Space>
          </Col>
        </Row>
      </div>

      <Spin spinning={loading}>
        <Row gutter={[16, 16]}>
          {books.map(book => (
            <Col xs={24} sm={12} md={8} lg={6} key={book.id}>
              <Card
                hoverable
                cover={
                  <div style={{ 
                    height: '240px', 
                    display: 'flex', 
                    alignItems: 'center',
                    justifyContent: 'center',
                    background: '#f5f5f5',
                    padding: '10px'
                  }}>
                    <Image
                      alt={book.name}
                      src={book.cover}
                      style={{ 
                        maxHeight: '100%', 
                        maxWidth: '100%',
                        objectFit: 'cover'
                      }}
                      fallback=""
                      preview={false}
                    />
                  </div>
                }
                actions={[
                  <Button 
                    type="text" 
                    icon={<EyeOutlined />} 
                    onClick={() => viewBookDetail(book.id)}
                  >
                    查看详情
                  </Button>,
                  <Button 
                    type="text" 
                    icon={<ShoppingCartOutlined />} 
                    onClick={() => addToCart(book)}
                  >
                    加入购物车
                  </Button>
                ]}
              >
                <Meta
                  title={
                    <div style={{ 
                      whiteSpace: 'nowrap', 
                      overflow: 'hidden', 
                      textOverflow: 'ellipsis' 
                    }}>
                      {book.name}
                    </div>
                  }
                  description={
                    <div>
                      <div style={{ 
                        color: '#666', 
                        marginBottom: 4,
                        whiteSpace: 'nowrap', 
                        overflow: 'hidden', 
                        textOverflow: 'ellipsis'
                      }}>
                        作者: {book.author}
                      </div>
                      <div style={{ 
                        color: '#666', 
                        marginBottom: 8,
                        whiteSpace: 'nowrap', 
                        overflow: 'hidden', 
                        textOverflow: 'ellipsis'
                      }}>
                        出版社: {book.publisher}
                      </div>
                      <div style={{ 
                        display: 'flex', 
                        justifyContent: 'space-between',
                        alignItems: 'center'
                      }}>
                        <span style={{ 
                          color: '#ff4d4f', 
                          fontWeight: 'bold',
                          fontSize: '16px'
                        }}>
                          ¥{book.price?.toFixed(2)}
                        </span>
                        <span style={{ color: '#999', fontSize: '12px' }}>
                          库存: {book.stock}
                        </span>
                      </div>
                    </div>
                  }
                />
              </Card>
            </Col>
          ))}
        </Row>

        {!loading && books.length === 0 && (
          <div style={{ 
            textAlign: 'center', 
            padding: '50px 0',
            color: '#999'
          }}>
            {searchText ? '没有找到相关书籍' : '暂无书籍'}
          </div>
        )}

        {pagination.total > 0 && (
          <div style={{ textAlign: 'center', marginTop: 32 }}>
            <Pagination
              current={pagination.current}
              pageSize={pagination.pageSize}
              total={pagination.total}
              showSizeChanger
              showQuickJumper
              showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`}
              onChange={handlePageChange}
              onShowSizeChange={handlePageChange}
            />
          </div>
        )}
      </Spin>
    </div>
  );
};

export default Books; 